package pro.cherish.knowledgecmomon.entity;

import lombok.Getter;
import pro.cherish.knowledgecmomon.enums.IErrorCode;
import pro.cherish.knowledgeutil.json.JsonUtilExt;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-02 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：BaseException
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-02 cherish
 */

public class BaseException extends RuntimeException implements Serializable {

    private static final long serialVersionUID = -422452041489241546L;
    /**
     * 异常代码
     */
    @Getter
    private String code;

    /**
     * 异常信息
     */
    @Getter
    private String msg;

    /**
     * 参数
     */
    @Getter
    private Object[] args;

    public BaseException(String msg) {
        this("500", msg);
    }


    public BaseException(IErrorCode error) {
        this(error.getCode(), error.getMsg());
    }

    public BaseException(String code, String msg) {
        this(code, msg, "");
    }

    public BaseException(IErrorCode error, Throwable e) {
        this(error.getCode(), error.getMsg(), e);
    }


    public BaseException(String code, String msg, Object... args) {
        super(formatMsg(msg, args) + " (" + code + ")");
        this.code = code;
        this.msg = formatMsg(msg, args);
        this.args = args;
    }

    protected static String formatMsg(String str, Object... args) {
        if (args == null || args.length == 0) {
            return str;
        }
        return MessageFormat.format(str, args);
    }

    @Override
    public String toString() {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", code);
        param.put("msg", formatMsg(msg, args));
        String json = JsonUtilExt.toJsonString(param);
        return json;
    }

    public static BaseException fromJson(String json) {
        return JsonUtilExt.fromJson(json, BaseException.class);
    }
}
